package com.it.gw.base

import DictVo
import LoginVo
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.DatePickerDialog
import android.content.Intent
import android.content.res.ColorStateList
import android.content.res.Resources
import android.media.metrics.Event
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.NumberPicker
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.viewbinding.ViewBinding
import com.google.android.material.datepicker.MaterialDatePicker
import com.google.android.material.timepicker.MaterialTimePicker
import com.google.android.material.timepicker.TimeFormat
import com.gyf.immersionbar.ImmersionBar
import com.gyf.immersionbar.ktx.statusBarHeight
import com.it.common.Constants
import com.it.common.bean.EventBean
import com.it.common.utils.ActivityUtils
import com.it.common.utils.CommonRxTimerTask
import com.it.common.utils.DialogUtils
import com.it.common.utils.UriUtils
import com.it.common.utils.hideKeyboardOnOutsideTouch
import com.it.common.utils.isNotEmpty
import com.it.data.manager.AppCacheManager
import com.it.data.manager.AppManager
import com.it.data.network.rsp.DictionariesVo
import com.it.data.network.rsp.NodeVo
import com.it.data.network.rsp.QuaTypeVo
import com.it.data.network.rsp.SttpVo
import com.it.gw.BuildConfig
import com.it.gw.R
import com.it.gw.databinding.DialogPickViewBinding
import com.it.gw.databinding.DialogSelectPicBinding
import com.it.gw.databinding.DialogWheelViewBinding
import com.it.gw.databinding.DialogYearMonthViewBinding
import com.it.gw.dialog.ProgressDialog
import com.it.gw.manager.DictionariesManager
import com.it.gw.modules.main.viewmodel.MainViewModel
import com.it.gw.modules.station.viewmodel.GQStationViewModel
import com.it.gw.modules.user.activity.LoginActivity
import com.tencent.mmkv.MMKV
import com.weigan.loopview.LoopView
import com.weigan.loopview.OnItemScrollListener
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale


/**
 *  @Description：Activity基础类
 *  @author：weishixiong
 *  @date：2023/3/28 14:25
 *
 */
abstract class BaseActivity<T : ViewBinding> : AppCompatActivity() {
    protected lateinit var binding: T
    val gqStationViewModel by viewModels<GQStationViewModel>()
    val mainViewModel by viewModels<MainViewModel>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d(javaClass.simpleName, "onCreate: ${javaClass.simpleName}")
        initStatus()
        setContentView()
        initObserver()
        initView()
        initData()
        initListener()
        hideKeyboardOnOutsideTouch()
        ActivityUtils.addActivity(this)

        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                Log.d("PhotoPicker=========", "Selected URI: ${uri.path}")
                val path = UriUtils.getPathForUri(this, uri)
                pickMediaAction?.invoke(path)

            } else {
                Log.d("PhotoPicker=========", "No media selected")
            }
        }
        EventBus.getDefault().register(this)

    }


    abstract fun initObserver()

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun eventBus(event: EventBean<*>) {
        val msgType = event.msgType
        Toast.makeText(this, "登录已过期", Toast.LENGTH_SHORT).show()
        when (msgType) {
            //收到退出登录
            Constants.MSG_LOGOUT -> {
                ProgressDialog.hide()
                AppCacheManager.clearAll()
                ActivityUtils.finishAll()
                startActivity(Intent(this, LoginActivity::class.java))
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        ActivityUtils.removeActivity(this)
        EventBus.getDefault().unregister(this)
    }

    override fun onResume() {
        super.onResume()
        AppManager.resumeActivity = this

    }

    abstract fun initListener()

    abstract fun initData()

    abstract fun initView()

    abstract fun setContentView()

    /**
     * 状态栏，导航栏的设置
     * @param statusBarLightFont Boolean false 文字暗色  true 文字亮色
     */
    open fun initStatus(statusBarLightFont: Boolean = false) {
        //隐藏导航栏
        supportActionBar?.hide()
        //沉侵式状态栏
        ImmersionBar.with(this).statusBarDarkFont(!statusBarLightFont).init()
        val statusBarHeight = statusBarHeight
        window.setFlags(
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
        );
        Log.d(javaClass.simpleName, "initStatus:${statusBarHeight} ")


    }

    fun setTitle(
        title: Int,
        isBack: Boolean? = false,
        ivRightRes1: Int? = null,
        tvRightRes1: Int? = null,
        backAction: (() -> Unit)? = null,
        ivRight1Action: (() -> Unit)? = null,
        tvRight1Action: (() -> Unit)? = null,
        textColorRes: Int = R.color.black,
        bgColorRes: Int = R.color.white,

        ) {
        val llTitleBg = binding.root.findViewById<LinearLayout>(R.id.ll_title_bg)
        val tvTitle = binding.root.findViewById<TextView>(R.id.tv_title)
        val ivLeft1 = binding.root.findViewById<ImageView>(R.id.iv_left1)
        val ivRight1 = binding.root.findViewById<ImageView>(R.id.iv_right1)
        val tvRight1 = binding.root.findViewById<TextView>(R.id.tv_right1)

        llTitleBg.setBackgroundColor(ContextCompat.getColor(this, bgColorRes))
        tvTitle.setTextColor(ContextCompat.getColor(this, textColorRes))
        tvTitle.setText(title)


        if (isBack == true) {
            ivLeft1.visibility = View.VISIBLE
            ivLeft1.imageTintList =
                ColorStateList.valueOf(ContextCompat.getColor(this, textColorRes))
            ivLeft1.setOnClickListener {
                finish()
            }
            //
            binding.root.findViewById<View>(R.id.v_back).setOnClickListener {
                finish()
            }
        } else {
            ivLeft1.visibility = View.GONE
        }


        if (ivRightRes1 != null) {
            ivRight1.visibility = View.VISIBLE
            ivRight1.imageTintList =
                ColorStateList.valueOf(ContextCompat.getColor(this, textColorRes))
            ivRight1.setImageResource(ivRightRes1)
            ivRight1.setOnClickListener {
                ivRight1Action?.invoke()
            }
        } else {
            ivRight1.visibility = View.GONE
        }

        if (tvRightRes1 != null) {
            tvRight1.visibility = View.VISIBLE
            tvRight1.setTextColor(ContextCompat.getColor(this, textColorRes))
            tvRight1.setText(tvRightRes1)
            tvRight1.setOnClickListener {
                tvRight1Action?.invoke()
            }
        } else {
            tvRight1.visibility = View.GONE
        }


    }

    fun setTitle(
        title: String,
        isBack: Boolean? = false,
        ivRightRes1: Int? = null,
        tvRightRes1: Int? = null,
        backAction: (() -> Unit)? = null,
        ivRight1Action: (() -> Unit)? = null,
        tvRight1Action: (() -> Unit)? = null,
        textColorRes: Int = R.color.black,
        bgColorRes: Int = R.color.white,

        ) {
        val llTitleBg = binding.root.findViewById<LinearLayout>(R.id.ll_title_bg)
        val tvTitle = binding.root.findViewById<TextView>(R.id.tv_title)
        val ivLeft1 = binding.root.findViewById<ImageView>(R.id.iv_left1)
        val ivRight1 = binding.root.findViewById<ImageView>(R.id.iv_right1)
        val tvRight1 = binding.root.findViewById<TextView>(R.id.tv_right1)

        llTitleBg.setBackgroundColor(ContextCompat.getColor(this, bgColorRes))
        tvTitle.setTextColor(ContextCompat.getColor(this, textColorRes))
        tvTitle.setText(title)


        if (isBack == true) {
            ivLeft1.visibility = View.VISIBLE
            ivLeft1.imageTintList =
                ColorStateList.valueOf(ContextCompat.getColor(this, textColorRes))
            ivLeft1.setOnClickListener {
                finish()
            }
            //
            binding.root.findViewById<View>(R.id.v_back).setOnClickListener {
                finish()
            }
        } else {
            ivLeft1.visibility = View.GONE
        }


        if (ivRightRes1 != null) {
            ivRight1.visibility = View.VISIBLE
            ivRight1.imageTintList =
                ColorStateList.valueOf(ContextCompat.getColor(this, textColorRes))
            ivRight1.setImageResource(ivRightRes1)
            ivRight1.setOnClickListener {
                ivRight1Action?.invoke()
            }
        } else {
            ivRight1.visibility = View.GONE
        }

        if (tvRightRes1 != null) {
            tvRight1.visibility = View.VISIBLE
            tvRight1.setTextColor(ContextCompat.getColor(this, textColorRes))
            tvRight1.setText(tvRightRes1)
            tvRight1.setOnClickListener {
                tvRight1Action?.invoke()
            }
        } else {
            tvRight1.visibility = View.GONE
        }


    }

    var list2: List<NodeVo>? = null
    var select2Position = 0
    var list3: List<NodeVo>? = null
    var select3Position = 0
    var addvcd: String? = null
    var sttp: String? = null
    var projecttype: String? = null
    var quedeal: String? = null
    var stnm: String? = null
    val selectTask = CommonRxTimerTask();

    //请选择行政区划
    @SuppressLint("RestrictedApi")
    fun showAddvcdWheelPickDialog(okAction: () -> Unit) {
        val depId = MMKV.defaultMMKV()
            .decodeParcelable(AppCacheManager.KEY_LOGIN_DATA, LoginVo::class.java)?.depId

        depId?.let { dId ->
            ProgressDialog.show(this)
            mainViewModel.getNodeByAd(depId = dId) {
                runOnUiThread {
                    ProgressDialog.hide()
                    if (it.result) {
                        if (it.data.isNotEmpty()) {
                            val dialogPickViewBinding =
                                DialogPickViewBinding.inflate(layoutInflater)
                            val addList = it.data
                            //设置1级节点
                            val list1 = addList?.filter { it.pid == "root0" }
                            val strList1 = list1?.map { v -> v.text }
                            dialogPickViewBinding.loopView1.setItems(strList1)
                            //设置2级节点，默认是第一个父亲的子节点
                            list2 = addList?.filter { it.pid == list1?.get(0)?.id }
                            val strList2 = list2?.map { v -> v.text }?.toMutableList()
                            strList2?.add(0, "请选择")
                            dialogPickViewBinding.loopView2.setItems(strList2)
                            //设置3级节点
                            list3 = addList?.filter { it.pid == list2?.get(0)?.id }
                            val strList3 = list3?.map { v -> v.text }?.toMutableList()

                            strList3?.add(0, "请选择")
                            dialogPickViewBinding.loopView3.setItems(strList3)
                            val dialog =
                                DialogUtils.getDialog(this, dialogPickViewBinding.root)
                            dialogPickViewBinding.tvCancel.setOnClickListener {
                                dialog.dismiss()
                            }
                            dialogPickViewBinding.tvOk.setOnClickListener {
                                dialog.dismiss()
                                okAction.invoke()

                            }

                            dialogPickViewBinding.loopView2.setOnItemScrollListener(object :
                                OnItemScrollListener {
                                override fun onItemScrollStateChanged(
                                    loopView: LoopView?,
                                    currentPassItem: Int,
                                    oldScrollState: Int,
                                    scrollState: Int,
                                    totalScrollY: Int
                                ) {
                                    select2Position = currentPassItem - 1
                                    if (select2Position < 0) {
                                        val strList3 = mutableListOf("请选择")
                                        dialogPickViewBinding.loopView3.setItems(strList3)

                                    } else {
                                        //设置3级节点
                                        val list3 =
                                            addList?.filter { it.pid == list2?.get(select2Position)?.id }
                                        val strList3 = list3?.map { v -> v.text }?.toMutableList()
                                        strList3?.add(0, "请选择")
                                        dialogPickViewBinding.loopView3.setItems(strList3)
                                        selectTask.cancel()
                                        selectTask.delayToMainThread(100) {
                                            dialogPickViewBinding.loopView3.setCurrentPosition(0)
                                        }


                                    }
                                }

                                override fun onItemScrolling(
                                    loopView: LoopView?,
                                    currentPassItem: Int,
                                    scrollState: Int,
                                    totalScrollY: Int
                                ) {
                                    select2Position = currentPassItem - 1
                                    if (select2Position < 0) {
                                        val strList3 = mutableListOf("请选择")
                                        dialogPickViewBinding.loopView3.setItems(strList3)
                                    } else {
                                        //设置3级节点
                                        list3 =
                                            addList?.filter { it.pid == list2?.get(select2Position)?.id }
                                        val strList3 = list3?.map { v -> v.text }?.toMutableList()
                                        strList3?.add(0, "请选择")
                                        dialogPickViewBinding.loopView3.setItems(strList3)
                                        selectTask.cancel()
                                        selectTask.delayToMainThread(100) {
                                            dialogPickViewBinding.loopView3.setCurrentPosition(0)
                                        }
                                    }
                                }

                            })

                            dialogPickViewBinding.loopView3.setOnItemScrollListener(object :
                                OnItemScrollListener {
                                override fun onItemScrollStateChanged(
                                    loopView: LoopView?,
                                    currentPassItem: Int,
                                    oldScrollState: Int,
                                    scrollState: Int,
                                    totalScrollY: Int
                                ) {
                                    select3Position = currentPassItem - 1

                                }

                                override fun onItemScrolling(
                                    loopView: LoopView?,
                                    currentPassItem: Int,
                                    scrollState: Int,
                                    totalScrollY: Int
                                ) {
                                    select3Position = currentPassItem - 1

                                }

                            })

                            dialog.show()
                        } else {
                            Toast.makeText(this, it.msg, Toast.LENGTH_LONG)
                                .show()
                        }

                    } else {
                        Toast.makeText(this, it.msg, Toast.LENGTH_LONG).show()
                    }

                }
            }


        }


    }

    val projecttypeList = mutableListOf(
        Pair<String, String>("0", "山洪站"),
        Pair<String, String>("1", "中小河流站"),
        Pair<String, String>("6", "防汛抗旱"),
        Pair<String, String>("10", "国控一期水位站"),
        Pair<String, String>("11", "国控一期管道站"),
        Pair<String, String>("12", "国控二期水位站"),
        Pair<String, String>("13", "国控二期管道流量站"),
        Pair<String, String>("14", "视频站"),
        Pair<String, String>("15", "图像站"),
        Pair<String, String>("8", "地方"),
        Pair<String, String>("9", "其他"),
    )

    fun showProjecttypeWheelViewDialog(okAction: (Int) -> Unit) {
        val dialogWheelViewBinding = DialogWheelViewBinding.inflate(layoutInflater)
        val list = projecttypeList?.map { v -> v.second }
        dialogWheelViewBinding.loopView.setItems(list)
        val dialog =
            DialogUtils.getDialog(this, dialogWheelViewBinding.root)
        dialogWheelViewBinding.tvCancel.setOnClickListener {
            dialog.dismiss()
        }
        dialogWheelViewBinding.tvOk.setOnClickListener {
            dialog.dismiss()
            val index = dialogWheelViewBinding.loopView.selectedItem
            okAction.invoke(index)

        }
        dialog.show()
    }


    val queDealList =
        mutableListOf(Pair<String, String>("1", "正常"), Pair<String, String>("0", "问题"))

    /**
     * 选择运维状态
     */
    fun showQuedealWheelViewDialog(okAction: (Int) -> Unit) {
        val dialogWheelViewBinding = DialogWheelViewBinding.inflate(layoutInflater)
        val list = queDealList?.map { v -> v.second }
        dialogWheelViewBinding.loopView.setItems(list)
        val dialog =
            DialogUtils.getDialog(this, dialogWheelViewBinding.root)
        dialogWheelViewBinding.tvCancel.setOnClickListener {
            dialog.dismiss()
        }
        dialogWheelViewBinding.tvOk.setOnClickListener {
            dialog.dismiss()
            val index = dialogWheelViewBinding.loopView.selectedItem
            okAction.invoke(index)

        }
        dialog.show()

    }

    var sttpList: MutableList<SttpVo>? = null
    fun showSttpWheelViewDialog(okAction: (Int) -> Unit) {
        ProgressDialog.show(this)
        gqStationViewModel.getSttp {
            runOnUiThread {
                ProgressDialog.hide()
                if (it.result) {
                    if (it.data.isNotEmpty()) {

                        val dialogWheelViewBinding = DialogWheelViewBinding.inflate(layoutInflater)
                        sttpList = it.data?.toMutableList()
                        val list = sttpList?.map { v -> v.key }
                        dialogWheelViewBinding.loopView.setItems(list)
                        val dialog =
                            DialogUtils.getDialog(this, dialogWheelViewBinding.root)
                        dialogWheelViewBinding.tvCancel.setOnClickListener {
                            dialog.dismiss()
                        }
                        dialogWheelViewBinding.tvOk.setOnClickListener {
                            dialog.dismiss()
                            val index = dialogWheelViewBinding.loopView.selectedItem
                            okAction.invoke(index)

                        }
                        dialog.show()
                    } else {
                        Toast.makeText(this, it.msg, Toast.LENGTH_LONG).show()
                    }

                } else {
                    Toast.makeText(this, it.msg, Toast.LENGTH_LONG).show()
                }

            }
        }

    }

    fun showYearMonthWheelViewDialog(okAction: (String, String) -> Unit) {
        val yearList = mutableListOf<String>()
        val monthList = mutableListOf<String>()
        for (i in 1980 until 2200) {
            yearList.add("${i}年")
        }
        for (i in 1 until 13) {
            monthList.add("${i}月")
        }


        val dialogYearMonthViewBinding = DialogYearMonthViewBinding.inflate(layoutInflater)

        dialogYearMonthViewBinding.loopView1.setItems(yearList)
        dialogYearMonthViewBinding.loopView2.setItems(monthList)
        dialogYearMonthViewBinding.loopView1.setCurrentPosition(40)

        val dialog =
            DialogUtils.getDialog(this, dialogYearMonthViewBinding.root)
        dialogYearMonthViewBinding.tvCancel.setOnClickListener {
            dialog.dismiss()
        }
        dialogYearMonthViewBinding.tvOk.setOnClickListener {
            dialog.dismiss()
            val year = yearList.get(dialogYearMonthViewBinding.loopView1.selectedItem)
            val month = monthList.get(dialogYearMonthViewBinding.loopView2.selectedItem)
            okAction.invoke(year, month)

        }
        dialog.show()
    }


    var quaTypeList: MutableList<QuaTypeVo>? = null
    var quaType: String? = null
    fun showQuaTypeWheelViewDialog(okAction: (Int) -> Unit) {
        ProgressDialog.show(this)
        mainViewModel.getQuaType {
            runOnUiThread {
                ProgressDialog.hide()
                if (it.result) {
                    if (it.data.isNotEmpty()) {
                        val dialogWheelViewBinding = DialogWheelViewBinding.inflate(layoutInflater)
                        quaTypeList = it.data?.toMutableList()

                        val list = quaTypeList?.map { v -> v.data_Name }
                        dialogWheelViewBinding.loopView.setItems(list)
                        val dialog =
                            DialogUtils.getDialog(this, dialogWheelViewBinding.root)
                        dialogWheelViewBinding.tvCancel.setOnClickListener {
                            dialog.dismiss()
                        }
                        dialogWheelViewBinding.tvOk.setOnClickListener {
                            dialog.dismiss()
                            val index = dialogWheelViewBinding.loopView.selectedItem
                            okAction.invoke(index)
                        }
                        dialog.show()
                    } else {
                        Toast.makeText(this, it.msg, Toast.LENGTH_LONG).show()
                    }

                } else {
                    Toast.makeText(this, it.msg, Toast.LENGTH_LONG).show()
                }

            }
        }

    }


    // 成员变量
    private val REQUEST_CODE_TAKE_PHOTO = 1
    private var photoFile: File? = null
    private var photoUri: Uri? = null
    private var takePhotoAction: ((String?) -> Unit)? = null

    // 调用相机拍照方法
    fun takePhoto(takePhotoAction: (String?) -> Unit) {
        this.takePhotoAction = takePhotoAction
        // 创建保存照片的文件
        photoFile = createImageFile()
        if (photoFile != null) {
            // 获取文件的Uri
            photoUri = FileProvider.getUriForFile(
                this,
                BuildConfig.APPLICATION_ID + ".fileprovider",
                photoFile!!
            )
            // 创建Intent
            val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            if (takePictureIntent.resolveActivity(packageManager) != null) {
                // 设置拍照后保存的Uri
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
                startActivityForResult(takePictureIntent, REQUEST_CODE_TAKE_PHOTO)
            }
        }
    }

    // 创建保存照片的文件
    private fun createImageFile(): File {
        val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
        val imageFileName = "JPEG_" + timeStamp + "_"
        val storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        val image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",  /* suffix */
            storageDir /* directory */
        )

        // 返回文件对象
        return image
    }

    // 处理拍照结果
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_TAKE_PHOTO && resultCode == RESULT_OK) {
            // 照片拍摄后的回调处理
            // 例如，可以将照片显示在ImageView中
            // ImageView imageView = findViewById(R.id.image_view);
            // imageView.setImageURI(photoUri);
            takePhotoAction?.invoke(photoFile?.path)

        }
    }

    lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>
    private var pickMediaAction: ((String?) -> Unit)? = null
    fun pickMedia(pickMediaAction: (String?) -> Unit) {
        this.pickMediaAction = pickMediaAction
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }


    /**
     * 选择拍照或者相册
     * @param vo PictureVo
     */
    fun showPicSelect(selectAction: (Int) -> Unit) {
        val dialogSelectPicBinding = DialogSelectPicBinding.inflate(layoutInflater)
        val dialog =
            DialogUtils.getDialog(this, dialogSelectPicBinding.root)
        dialogSelectPicBinding.rlCancel.setOnClickListener {
            dialog.dismiss()
        }
        dialogSelectPicBinding.rlCamera.setOnClickListener {
            dialog.dismiss()
            selectAction.invoke(1)

        }
        dialogSelectPicBinding.rlPhoto.setOnClickListener {
            dialog.dismiss()
            selectAction.invoke(2)
        }
        dialog.show()

    }

    fun showSelectWheelViewDialog(okAction: (Int) -> Unit, dictVoList: List<DictVo>) {
        val dialogWheelViewBinding = DialogWheelViewBinding.inflate(layoutInflater)
        val list = dictVoList?.map { v -> v.dataName }
        dialogWheelViewBinding.loopView.setItems(list)
        val dialog =
            DialogUtils.getDialog(this, dialogWheelViewBinding.root)
        dialogWheelViewBinding.tvCancel.setOnClickListener {
            dialog.dismiss()
        }
        dialogWheelViewBinding.tvOk.setOnClickListener {
            dialog.dismiss()
            val index = dialogWheelViewBinding.loopView.selectedItem
            okAction.invoke(index)

        }
        dialog.show()
    }

    /**
     * 公共字典选择器
     * @param okAction Function1<Int, Unit>
     * @param dataList List<DictionariesVo>
     */
    fun showDictionariesWheelViewDialog(okAction: (Int) -> Unit, dataList: List<DictionariesVo>) {
        val dialogWheelViewBinding = DialogWheelViewBinding.inflate(layoutInflater)
        val list = dataList?.map { v -> v.ITEMNAME }
        dialogWheelViewBinding.loopView.setItems(list)
        val dialog =
            DialogUtils.getDialog(this, dialogWheelViewBinding.root)
        dialogWheelViewBinding.tvCancel.setOnClickListener {
            dialog.dismiss()
        }
        dialogWheelViewBinding.tvOk.setOnClickListener {
            dialog.dismiss()
            val index = dialogWheelViewBinding.loopView.selectedItem
            okAction.invoke(index)

        }
        dialog.show()
    }

    fun showDateTimePickerDialog(selectTimeAction: (String) -> Unit) {
        // 显示日期选择器
        val datePicker = MaterialDatePicker.Builder.datePicker()
            .setTitleText("选择日期")
            .build()

        datePicker.addOnPositiveButtonClickListener { selectedDateInMillis ->
            // 显示时间选择器
            val timePicker = MaterialTimePicker.Builder()
                .setTimeFormat(TimeFormat.CLOCK_24H)
                .setHour(12)
                .setMinute(0)
                .setTitleText("选择时间")
                .build()

            timePicker.addOnPositiveButtonClickListener {
                // 合并日期和时间
                val calendar = Calendar.getInstance()
                calendar.timeInMillis = selectedDateInMillis
                calendar.set(Calendar.HOUR_OF_DAY, timePicker.hour)
                calendar.set(Calendar.MINUTE, timePicker.minute)

                // 格式化日期和时间
                val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
                val selectedDateTime = dateFormat.format(calendar.time)
                selectTimeAction.invoke(selectedDateTime)
                Log.d(
                    javaClass.simpleName,
                    "showDateTimePickerDialog: 选择的日期和时间: $selectedDateTime"
                )

            }

            timePicker.show(supportFragmentManager, "TIME_PICKER")
        }

        datePicker.show(supportFragmentManager, "DATE_PICKER")
    }


    fun showDatePickerDialog(selectDateAction: (String) -> Unit) {
        // 显示日期选择器
        val datePicker = MaterialDatePicker.Builder.datePicker()
            .setTitleText("选择日期")
            .build()

        datePicker.addOnPositiveButtonClickListener { selectedDateInMillis ->
            // 格式化日期
            val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
            val selectedDate = dateFormat.format(selectedDateInMillis)
            selectDateAction.invoke(selectedDate)
            Log.d(
                javaClass.simpleName,
                "showDatePickerDialog: 选择的日期: $selectedDate"
            )
        }

        // 注意：这里假设你在FragmentActivity或者其子类（如AppCompatActivity）中调用此方法
        // 如果是在Fragment中调用，请使用childFragmentManager或者parentFragmentManager替代supportFragmentManager
        datePicker.show(supportFragmentManager, "DATE_PICKER")
    }

    fun showYearMonthPickerDialog(selectDateAction: (String) -> Unit) {
        // 使用Calendar实例来获取当前年月
        val calendar = Calendar.getInstance()
        val currentYear = calendar.get(Calendar.YEAR)
        val currentMonth = calendar.get(Calendar.MONTH)

        // 创建自定义对话框
        val dialogView = LayoutInflater.from(this).inflate(R.layout.year_month_picker, null)
        val yearPicker = dialogView.findViewById<NumberPicker>(R.id.yearPicker)
        val monthPicker = dialogView.findViewById<NumberPicker>(R.id.monthPicker)

        // 设置年份选择器
        yearPicker.minValue = 1900
        yearPicker.maxValue = currentYear
        yearPicker.value = currentYear

        // 设置月份选择器
        monthPicker.minValue = 1
        monthPicker.maxValue = 12
        monthPicker.value = currentMonth + 1

        // 创建对话框
        val builder = AlertDialog.Builder(this)
        builder.setView(dialogView)
        val dialog = builder.create()

        // 设置确定按钮点击事件
        dialogView.findViewById<Button>(R.id.btnOk).setOnClickListener {
            val selectedYear = yearPicker.value
            val selectedMonth = monthPicker.value
            val selectedDate = "$selectedYear-${String.format("%02d", selectedMonth)}"
            selectDateAction.invoke(selectedDate)
            Log.d(javaClass.simpleName, "showYearMonthPickerDialog: 选择的年月: $selectedDate")
            dialog.dismiss()
        }

        // 设置取消按钮点击事件
        dialogView.findViewById<Button>(R.id.btnCancel).setOnClickListener {
            dialog.dismiss()
        }

        // 显示对话框
        dialog.show()
    }

    fun showYearPickerDialog(selectYearAction: (Int) -> Unit) {
        // 使用Calendar实例来获取当前年份
        val calendar = Calendar.getInstance()
        val currentYear = calendar.get(Calendar.YEAR)

        // 创建自定义对话框
        val dialogView = LayoutInflater.from(this).inflate(R.layout.year_picker, null)
        val yearPicker = dialogView.findViewById<NumberPicker>(R.id.yearPicker)

        // 设置年份选择器
        yearPicker.minValue = 1900
        yearPicker.maxValue = currentYear
        yearPicker.value = currentYear

        // 创建对话框
        val builder = AlertDialog.Builder(this)
        builder.setView(dialogView)
        val dialog = builder.create()

        // 设置确定按钮点击事件
        dialogView.findViewById<Button>(R.id.btnOk).setOnClickListener {
            val selectedYear = yearPicker.value
            selectYearAction.invoke(selectedYear)
            Log.d(javaClass.simpleName, "showYearPickerDialog: 选择的年份: $selectedYear")
            dialog.dismiss()
        }

        // 设置取消按钮点击事件
        dialogView.findViewById<Button>(R.id.btnCancel).setOnClickListener {
            dialog.dismiss()
        }

        // 显示对话框
        dialog.show()
    }


    /**
     * 选择任务类型
     */
    fun showOrderTypeWheelViewDialog(okAction: (Int) -> Unit) {
        val dialogWheelViewBinding = DialogWheelViewBinding.inflate(layoutInflater)
        val list = DictionariesManager.orderTypeList?.map { v -> v.second }
        dialogWheelViewBinding.loopView.setItems(list)
        val dialog =
            DialogUtils.getDialog(this, dialogWheelViewBinding.root)
        dialogWheelViewBinding.tvCancel.setOnClickListener {
            dialog.dismiss()
        }
        dialogWheelViewBinding.tvOk.setOnClickListener {
            dialog.dismiss()
            val index = dialogWheelViewBinding.loopView.selectedItem
            okAction.invoke(index)

        }
        dialog.show()

    }

    val orderStatusList =
        mutableListOf(
            Pair<String, String>("0", "未完成"),
            Pair<String, String>("1", "已完成"),
        )

    /**
     * 选择任务状态
     */
    fun showOrderStatusWheelViewDialog(okAction: (Int) -> Unit) {
        val dialogWheelViewBinding = DialogWheelViewBinding.inflate(layoutInflater)
        val list = orderStatusList?.map { v -> v.second }
        dialogWheelViewBinding.loopView.setItems(list)
        val dialog =
            DialogUtils.getDialog(this, dialogWheelViewBinding.root)
        dialogWheelViewBinding.tvCancel.setOnClickListener {
            dialog.dismiss()
        }
        dialogWheelViewBinding.tvOk.setOnClickListener {
            dialog.dismiss()
            val index = dialogWheelViewBinding.loopView.selectedItem
            okAction.invoke(index)

        }
        dialog.show()

    }

}